package com.plugin.mybtaisxplus.util;

import com.plugin.mybtaisxplus.MyBtaisXplus;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.Properties;

/**
 * 模板渲染服务
 * 封装 Velocity 引擎的初始化和模板渲染逻辑。
 */
public class TemplateService {

    private final VelocityEngine velocityEngine;

    /**
     * 构造函数在实例化时初始化 Velocity 引擎。
     * 这里处理了棘手的类加载器问题。
     */
    public TemplateService() {
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(MyBtaisXplus.class.getClassLoader());

            velocityEngine = new VelocityEngine();
            Properties p = new Properties();
            // 使用 Velocity 2.x 推荐的新配置键
            p.setProperty(RuntimeConstants.RESOURCE_LOADERS, "classpath");
            p.setProperty("resource.loader.classpath.class", ClasspathResourceLoader.class.getName());
            velocityEngine.init(p);
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }

    /**
     * 渲染模板。
     * @param templatePath 模板在 resources FOLDER下的路径 (e.g., "templates/entity.vm")
     * @param context      包含模板所需数据的数据上下文
     * @return 渲染后的字符串内容
     */
    public String render(String templatePath, VelocityContext context) {
        // 在渲染时也切换类加载器，保证 Velocity 内部操作的上下文一致性
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(MyBtaisXplus.class.getClassLoader());

            Template template = velocityEngine.getTemplate(templatePath, "UTF-8");
            StringWriter writer = new StringWriter();
            template.merge(context, writer);
            return writer.toString();
        } finally {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }
}